package com.frikinet.tools.gui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

import javax.swing.JCheckBoxMenuItem;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JToggleButton;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class ActionHandler implements ActionListener
{
	private Object implementer = null;
	private String paramSeparator = "/";
	private String wordSeparator = "\\.";
	private Logger log = LoggerFactory.getLogger(ActionHandler.class);

	public ActionHandler(Object implementer)
	{
		this(implementer, "/");
	}

	public ActionHandler(Object implementer, String paramSeparator)
	{
		this.implementer = implementer;
		this.paramSeparator = paramSeparator;
		this.log = LoggerFactory.getLogger(implementer.getClass());
	}

	public void actionPerformed(ActionEvent e)
	{
		Class<?> clazz = implementer.getClass();
		String actionCommand = e.getActionCommand().split(paramSeparator)[0];
		String[] actionParams = Arrays.copyOfRange(e.getActionCommand().split(paramSeparator), 1, e.getActionCommand().split(paramSeparator).length);
		actionCommand = actionCommand.replaceAll(wordSeparator, "_");

		// calculate params
		List<String> params = new ArrayList<String>();

		/*
		// if the source is a JCheckBoxMenuItem add a boolean value with its state
		if (e.getSource() instanceof JCheckBoxMenuItem)
		{
			params.add(Boolean.valueOf(((JCheckBoxMenuItem) e.getSource()).getState()).toString());
		}
		// if the source is a JRadioButtonMenuItem add a boolean value with its state
		else if (e.getSource() instanceof JRadioButtonMenuItem)
		{
			params.add(Boolean.valueOf(((JRadioButtonMenuItem) e.getSource()).isSelected()).toString());
		}
		// if the source is an instance of JToggleButton (JCheckBox, JRadioButton...) add a boolean value
		// with its state
		else if (e.getSource() instanceof JToggleButton)
		{
			params.add(Boolean.valueOf(((JToggleButton) e.getSource()).isSelected()).toString());
		}*/
		// add the rest of params
		for (String param : actionParams)
		{
			params.add(param);
		}

		// search the method to call
		boolean found = false;
		for (Method method : clazz.getMethods())
		{
			if (method.getName().startsWith("action_"))
			{
				String methodAction = method.getName().replaceAll("action_", "");
				Class<?> paramClasses[] = method.getParameterTypes();
				// if the function name and number of parameters match...
				if (methodAction.equals(actionCommand) && params.size() == paramClasses.length)
				{
					try
					{
						List<Object> functionParams = new ArrayList<Object>();
						Iterator<String> itParams = params.iterator();
						for (Class<?> paramClass : paramClasses)
						{
							String param = itParams.next();
							
							//check first Object level keywords for param
							if(param.equals("source") && paramClass.isInstance(e.getSource()))
							{
								functionParams.add(e.getSource());
							}
							
							//check for classes
							else if (paramClass == Integer.class || paramClass == int.class)
							{
								functionParams.add(new Integer(param));
							}
							else if (paramClass == Long.class || paramClass == long.class)
							{
								functionParams.add(new Long(param));
							}
							else if (paramClass == Double.class || paramClass == double.class)
							{
								functionParams.add(new Double(param));
							}
							else if (paramClass == Float.class || paramClass == float.class)
							{
								functionParams.add(new Float(param));
							}
							else if (paramClass == Boolean.class || paramClass == boolean.class)
							{
								//check for keywords
								if(param.equals("state"))
								{
									param = getState(e.getSource());
								}
								functionParams.add(new Boolean(param));
							}
							else if (paramClass == String.class)
							{
								functionParams.add(param);
							}
							else if (paramClass == ActionEvent.class)
							{
								if(param.equals("event"))
								{
									functionParams.add(e);
								}
							}
							else
							{
								boolean serializable = false;
								Class<?> currentClass = paramClass;
								while(!serializable && currentClass.getSuperclass()!=null)
								{
									for (Class<?> interfaceClass : currentClass.getInterfaces())
									{
										if (interfaceClass == Serializable.class)
										{
											functionParams.add(stringToObject(param));
											serializable = true;
											break;
										}
									}
									currentClass = currentClass.getSuperclass();
								}
							}
						}
						found = true;
						method.invoke(implementer, functionParams.toArray());
						break;
					}
					catch (Exception ex)
					{
						ex.printStackTrace();
					}
				}
			}
		}
		if(!found)
		{
			log.warn("Action handler method not found: action_"+actionCommand);
		}
	}
	
	private String getState(Object o)
	{
		String param = "false";
		// if the source is a JCheckBoxMenuItem
		if (o instanceof JCheckBoxMenuItem)
		{
			param = Boolean.valueOf(((JCheckBoxMenuItem) o).getState()).toString();
		}
		// if the source is a JRadioButtonMenuItem
		else if (o instanceof JRadioButtonMenuItem)
		{
			param = Boolean.valueOf(((JRadioButtonMenuItem) o).isSelected()).toString();
		}
		// if the source is an instance of JToggleButton (JCheckBox, JRadioButton...)
		else if (o instanceof JToggleButton)
		{
			param = Boolean.valueOf(((JToggleButton) o).isSelected()).toString();
		}
		return param;
	}

	public String objectToString(Object o)
	{
		try
		{
			BASE64Encoder encoder = new BASE64Encoder();
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			ObjectOutputStream serializer = new ObjectOutputStream(out);
			serializer.writeObject(o);
			return encoder.encode(out.toByteArray());
		}
		catch (IOException ioe)
		{
			ioe.printStackTrace();
		}
		return null;
	}

	public Object stringToObject(String s)
	{
		try
		{
			BASE64Decoder decoder = new BASE64Decoder();
			byte[] bytes = decoder.decodeBuffer(s);
			ByteArrayInputStream in = new ByteArrayInputStream(bytes);
			ObjectInputStream deserializer = new ObjectInputStream(in);
			return deserializer.readObject();
		}
		catch (IOException ioe)
		{
			ioe.printStackTrace();
		}
		catch (ClassNotFoundException cnfe)
		{
			cnfe.printStackTrace();
		}
		return null;
	}

	public Object getImplementer()
	{
		return implementer;
	}

	public void setImplementer(Object implementer)
	{
		this.implementer = implementer;
	}

	public String getParamSeparator()
	{
		return paramSeparator;
	}

	public void setParamSeparator(String paramSeparator)
	{
		this.paramSeparator = paramSeparator;
	}

	public String getWordSeparator()
	{
		return wordSeparator;
	}

	public void setWordSeparator(String wordSeparator)
	{
		this.wordSeparator = wordSeparator;
	}
}
